import { Component, OnInit, ViewChild, Injector } from '@angular/core';
import { _HttpClient, ModalHelper } from '@delon/theme';
import { SimpleTableColumn, SimpleTableComponent, SimpleTableButton } from '@delon/abc';
import { SFSchema } from '@delon/form';
import { NzTreeNode, NzModalService, NzMessageService, NzFormatEmitEvent } from 'ng-zorro-antd';
import { BaseController } from '@shared/base-controller';
import { FormBuilder } from '@angular/forms';
import { Constant } from '@core/constant';
import { UserService } from '../../../service/user/user.service';
import { catchError } from 'rxjs/operators';
import { of } from 'rxjs';
import { ShopEditComponent } from './edit/edit.component';

@Component({
  selector: 'admin-shop-list',
  templateUrl: './shop-list.component.html',
})
export class ShopListComponent extends BaseController implements OnInit {
  
  // 分类节点集合
  nodes = [];    
  // 当前被选中的节点
  currentNode: NzTreeNode = null;
  searchValue

  ps = 10;
  q: any = {
    parentId: "-1",
    name: ""
  };
  url = this.userService.secondList();
  data = [];
  @ViewChild('st') st: SimpleTableComponent;

  columns: SimpleTableColumn[] = [           
      { title: '账号', index: 'childUserName', i18n: 'account'},            
      { title: '名称', index: 'childName', i18n: 'name'},
      { title: '联系人', index: 'link_man', i18n: 'contact'},
      { title: '电话', index: 'tel', i18n: 'tel' },
      { title: 'Email', index: 'email', i18n: 'email' },      
      { title: '状态', index: 'is_disabled', i18n: 'status', render: 'isDisabled' },    
      {        
        title: '操作',
        buttons: [        
          { 
            text: '编辑',
            i18n: 'edit',
            type: 'modal',
            component: ShopEditComponent,
            paramName: 'record',            
            size: 600,      
            modal: {modalOptions: {nzStyle: {'top': '24px'}}},      
            click: (record: any, modal: any) => this.st.reload()
          },
          {
            text: '禁用',
            i18n: 'disable',
            pop: true,
            popTitle: 'Account disable?',                    
            iif: (item: any, btn: SimpleTableButton, column: SimpleTableColumn) => {
              return item.is_disabled === '0';
            },
            click: (record: any) => this.disable(record.child_id)
          },
          {
            text: '解禁',
            i18n: 'enable',       
            pop: true,
            popTitle: 'Account enable?',                   
            iif: (item: any, btn: SimpleTableButton, column: SimpleTableColumn) => {
              return item.is_disabled === '1';
            },
            click: (record: any) =>this.enable(record.child_id)
          }
        ]
      }    
  ];

  constructor(
    private modalService: NzModalService,
    public msg: NzMessageService, 
    private modalSrv: ModalHelper,        
    private fb: FormBuilder,
    private userService: UserService,  
    public injector: Injector ,
    private cnt: Constant
  ) {
    super(injector);
  }

  ngOnInit() {
    this.loadTree();
  }


  loadTree() {
    this.userService.agentTree().pipe(
        catchError(err => {                             
            return of(err);
        })
    ).subscribe(list => {            
        this.nodes = [];
        let o = this.replaceKeysDeep(list, this.mapShortToLong);            
        for (let index = 0; index < o.length; index++) {
            this.nodes.push(
                new NzTreeNode(o[index])
            );
        }   
    })
  }

  mapShortToLong: any = {
      "id": "key",
      "label": "title"
  };

  mouseAction(name: string, e: NzFormatEmitEvent): void { 
    if (name === 'click') {            
      if (e.node.isSelected) {            
        this.currentNode = e.node;   
        if (e.node.origin.level === 'SECOND') {
            this.q.parentId = e.node.key;
            this.st.load(1, this.q);          
        }
      } else {
          this.q.parentId = "-1";
          this.st._data = [];             
      }
    } else if (name === 'expand') {
        if (e.node.getChildren().length === 0 && e.node.isExpanded && e.node.origin.level === 'FIRST') {
            this.userService.childTree(e.node.key).subscribe(data => {
                let o = this.replaceKeysDeep(data, this.mapShortToLong);            
                let child = [];
                for (let index = 0; index < o.length; index++) {
                    child.push(
                        new NzTreeNode(o[index])
                    );
                }  
                e.node.addChildren(child); 
            })
        }        
    } 
  }

  addClient() {
    if (!this.currentNode || this.currentNode.origin.level !== 'SECOND') {
      this.msg.warning("Please select one 2nd customer");
      return;
    }
    this.modalSrv.static(ShopEditComponent, {parentId: this.currentNode.key}, 600, {nzStyle: {'top': '24px'}}).subscribe((e) => {
        this.st.load(1, this.q);            
    });

  }

  enable(id) {
    this.userService.enable(id).pipe(
        catchError(err => {                             
            return of(err);
        })
    ).subscribe(ret=>{
        if (ret.status === 200) {
            this.msg.success('Successful');
            this.st.load(1, this.q);         
        } else {
            this.msg.error(ret.message);
        }
    });
  }

  disable(id) {
    this.userService.disable(id).pipe(
        catchError(err => {                             
            return of(err);
        })
    ).subscribe(ret=>{
        if (ret.status === 200) {
            this.msg.success('Successful');
            this.st.load(1, this.q);         
        } else {
            this.msg.error(ret.message);
        }
    });
  }

}
